<script setup lang="ts">
import { onMounted, onUnmounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@vben/stores';
import { Bell } from '@vben/icons';
import { UserDropdown } from '@vben/layouts';
import { useMessage } from '#/hooks/useMessage';
import { useUserDropdown } from '#/hooks/useUserDropdown';
import { DEFAULT_HOME_PATH } from '#/utils/constants';

defineOptions({ name: 'UserLayout' });
const userStore = useUserStore();
const { fetchUnreadCount, resetMessage, badgeCount, showDot } = useMessage();
const router = useRouter();
const route = useRoute();

// 使用 UserDropdown hooks
const {
  isLogin,
  userDropdownProps,
  handleLogout
} = useUserDropdown({
  showPersonalCenter: true,
  showAdminMenu: route.path !== '/test/explainCore'
});

// 定时器引用
let refreshTimer: NodeJS.Timeout | null = null;

const handleTitleClick = () => {
  router.push(DEFAULT_HOME_PATH);
};

// 处理消息图标点击事件
const handleMessageClick = () => {
  // 可以跳转到消息页面或显示消息弹窗
  router.push('/lesson/personalCenter/userMessage');
};

// 启动定时刷新未读消息数量
const startMessageRefresh = () => {
  if (!isLogin.value) return;

  // 立即获取一次
  fetchUnreadCount();

  // 每30秒刷新一次
  refreshTimer = setInterval(() => {
    if (isLogin.value && !document.hidden) {
      fetchUnreadCount();
    }
  }, 5 * 60 * 1000);
};

// 停止定时刷新
const stopMessageRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
};

// 处理页面可见性变化
const handleVisibilityChange = () => {
  if (!document.hidden && isLogin.value) {
    // 页面变为可见时，立即刷新一次未读消息数量
    fetchUnreadCount();
  }
};

// 组件挂载时启动定时刷新
onMounted(() => {
  if (isLogin.value) {
    startMessageRefresh();
  }

  // 监听页面可见性变化
  document.addEventListener('visibilitychange', handleVisibilityChange);
});

// 组件卸载时清理定时器
onUnmounted(() => {
  stopMessageRefresh();
  document.removeEventListener('visibilitychange', handleVisibilityChange);
});

// 监听登录状态变化
watch(isLogin, (newIsLogin: boolean) => {
  if (newIsLogin) {
    startMessageRefresh();
  } else {
    stopMessageRefresh();
    resetMessage();
  }
});
</script>
<template>
  <div class="user-layout">
    <div class="flex items-center justify-between">
      <div class="auth-title flex h-[65px] cursor-pointer items-center pl-[20px] pr-[20px]" @click="handleTitleClick">
        <img :src="userStore.tenant?.loginUrl" alt="" class="mr-[4px] w-[32px]" />
        <span class="text-[18px] font-bold">{{ userStore.tenant?.shortName }}</span>
      </div>
      <div class="flex items-center">
        <VbenIconButton class="bell-button cursor-pointer text-foreground relative" @click="handleMessageClick">
          <span class="bg-[#E5484D] absolute right-0.5 top-0.5 h-2 w-2 rounded"></span>
          <Bell class="text-[24px]" />
        </VbenIconButton>
        <UserDropdown v-bind="userDropdownProps" tag-text="" @logout="handleLogout" />
      </div>
    </div>
  </div>
</template>
<style lang="less" scoped></style>
